package 练习06_线程池模拟批量导入数据;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @ClassName: TestThreadpoolImport01
 * @Author: AllenSun
 * @Date: 2022/3/22 下午10:29
 */
public class TestThreadpoolImport02 {

    private static ThreadPoolExecutor executor = new ThreadPoolExecutor(0,25,100L,
            TimeUnit.SECONDS,new LinkedBlockingQueue<>(),new ThreadPoolExecutor.CallerRunsPolicy());
    public static void main(String[] args) {
        Student student = null;
        List<Student> studentList = new ArrayList<>();
        int age = 0;
        int heigh = 0;
        //添加50万个数据
        for (int i=0;i<500000;i++) {
            age = (int) Math.floor((Math.random() * 10) + 20);
            heigh = (int) Math.floor((Math.random() * 160) + 180);
            student = new Student("name"+i,age,heigh,"玩");
            studentList.add(student);
        }

        long start = System.currentTimeMillis();

        //在线程池执行之前，给计数器指定数值（与要执行代码的次数一致）也就是students.size()
        CountDownLatch countDownLatch = new CountDownLatch(studentList.size());

        for (Student student1:studentList) {
            //模拟对数据信息进行二次处理
            executor.submit(()->{
                try {
                    student1.setName(student1.getName()+"这是后缀");
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    //每执行一次数值减少一
                    countDownLatch.countDown();
                    //也可以给await()设置超时时间，如果超过300s（也可以是时，分）则不再等待，直接执行下面代码。
                    //countDownLatch.await(300,TimeUnit.SECONDS);
                }
            });
        }
        try {
            //等待计数器归零
            countDownLatch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        long end = System.currentTimeMillis();
        System.out.println("添加数量："+studentList.stream().filter(x->x.getName().contains("这是后缀")).count());
        System.out.println("花费时间："+(end-start));


        //输出的数据是
        // 添加数量：500000
        // 花费时间：334
        //是50w，主线程等待所有子线程执行结束后才结束

    }
}
